package com.efounder.zone.activity;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.activity.RecorderActivity;
import com.efounder.chat.utils.FileSizeUtil;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.chat.utils.ThreadPoolUtils;
import com.efounder.chat.view.SendImgProgressView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity;
import com.efounder.ui.util.DisplayUtil;
import com.efounder.util.AppContext;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.zone.R;
import com.efounder.zone.adapter.WriteSelectImageAdapter;
import com.efounder.zone.bean.TalksBean;
import com.efounder.zone.bean.ZoneCloudFile;
import com.efounder.zone.util.CreateBeanUtil;
import com.efounder.zone.util.ZoneRequestUtil;
import com.efounder.zone.widget.AddZonePopWindow;
import com.utilcode.util.DeviceUtils;
import com.utilcode.util.FileUtils;
import com.utilcode.util.JFStringUtil;
import com.utilcode.util.KeyboardUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.chat.fragment.ChatSenderFragment.chatpath;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.pansoft.chat.photo.JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE;

/**
 * 发送动态界面
 *
 * @author will
 */
public class SendPostActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivBack;
    private TextView tvTitle;
    private ImageView ivAdd;
    private TextView tvSend;

    private EditText etInput;
    private LinearLayout llPhoto;
    private RelativeLayout llWebLayout;
    private EditText etUrl;
    private SeekBar seekbar;
    private WebView webView;
    private GridView gridView;
    /**
     * 视频缩略图显示
     */
    private ImageView ivVideoImage;
    private SendImgProgressView videoProgressView;
    private RelativeLayout rlVideo;
    private TextView tvWebViewHeightView;
    private ImageView ivVideo, ivWeb, ivPhoto;

    private WriteSelectImageAdapter adapter;

    private String mTitle;
    /**
     * 动态类型 说说为1 网页为2 视频为3 初始为0，可以选择其他
     */
    private int mDynamicType = 0;
    private String deviceModel;
    /**
     * 和选图联动的图片list
     */
    private ArrayList<ZoneCloudFile> mPictureList = new ArrayList<>();
    /**
     * 图片的url list
     */
    private ArrayList<String> imgUrlList = new ArrayList<>();
    /**
     * 视频本地路径
     */
    private String video_path = "";
    /**
     * 是否正在发送中
     */
    private boolean isSending;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mobile_zone_activity_send_post);
        deviceModel = DeviceUtils.getModel();
        isSending = false;
        initView();
        resetType();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoadingDataUtilBlack.dismiss();
//        LogUtils.e("aaaaaa");
//        finish();
    }

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivAdd = (ImageView) findViewById(R.id.iv_add);
        tvSend = (TextView) findViewById(R.id.tv_save);
        rlVideo = (RelativeLayout) findViewById(R.id.rl_video);
        ImageView ivVideoDelete = (ImageView) findViewById(R.id.iv_video_delete);
        ivVideoDelete.setOnClickListener(this);
        tvSend.setVisibility(View.VISIBLE);
        ivVideoImage = (ImageView) findViewById(R.id.video_cover_1);
        videoProgressView = (SendImgProgressView) findViewById(R.id.video_progressView);
        tvSend.setOnClickListener(this);
        etInput = (EditText) findViewById(R.id.et_input);
        llPhoto = (LinearLayout) findViewById(R.id.ll_photo);
        llWebLayout = (RelativeLayout) findViewById(R.id.ll_web_layout);
        etUrl = (EditText) findViewById(R.id.et_url);
//        seekbar = (SeekBar) findViewById(R.id.seekbar);
        webView = (WebView) findViewById(R.id.webView);
        gridView = (GridView) findViewById(R.id.gridview);
        initGridListener();
//        tvWebViewHeightView = (TextView) findViewById(R.id.tv_title2);
        ImageView ivWebDelete = (ImageView) findViewById(R.id.iv_web_delete);
        ivWebDelete.setOnClickListener(this);
        tvSend.setText(ResStringUtil.getString(R.string.zone_publish));
        tvTitle.setText(ResStringUtil.getString(R.string.zone_publish_ss));
        initBottomView();
        etInput.post(new Runnable() {
            @Override
            public void run() {
                etInput.setFocusableInTouchMode(true);
                etInput.requestFocus();
                KeyboardUtils.showSoftInput(etInput);
            }
        });

    }

    private void resetType() {
        //文字说说，照片说说
        if (mDynamicType == 1) {
            //只有照片可点击
            ivPhoto.setImageAlpha(255);
            ivVideo.setImageAlpha(128);
            ivWeb.setImageAlpha(128);
            llWebLayout.setVisibility(View.GONE);
            llPhoto.setVisibility(View.VISIBLE);
            rlVideo.setVisibility(View.GONE);
            adapter = new WriteSelectImageAdapter(this, mPictureList);
            adapter.setOnImgRemovedListener(new WriteSelectImageAdapter.OnImgRemovedListener() {
                @Override
                public void onImgRemoved(int position) {
                    if (isSending) {
                        ToastUtils.showShort(ResStringUtil.getString(R.string.zone_send_not_delete));
                        return;
                    }
                    mPictureList.remove(position);
                    adapter.notifyDataSetChanged();
                    if (mPictureList.size() == 0) {
                        mDynamicType = 0;
                        resetType();
                    }
                }
            });
            gridView.setAdapter(adapter);
        } else if (mDynamicType == 3) {
            //视频说说，只有视频可点击
            ivPhoto.setImageAlpha(128);
            ivVideo.setImageAlpha(255);
            ivWeb.setImageAlpha(128);
            rlVideo.setVisibility(View.GONE);
            llWebLayout.setVisibility(View.GONE);
            llPhoto.setVisibility(View.GONE);
        } else if (mDynamicType == 2) {
            //网页说说，只有网页可点击
            ivPhoto.setImageAlpha(128);
            ivVideo.setImageAlpha(128);
            ivWeb.setImageAlpha(255);
            llPhoto.setVisibility(View.GONE);
            llWebLayout.setVisibility(View.VISIBLE);
            rlVideo.setVisibility(View.GONE);
//            seekbar.setMax(200);
//            seekbar.setProgress(0);
//            initWebListener();
            //获取剪贴板管理器：
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            if (cm.getText() != null) {
                //剪贴板有内容，判断是否是网址，加载webView
                String text = cm.getText().toString();
                if (JFStringUtil.isHttpUrl(text)) {
                    LinearLayout.LayoutParams layoutParams =
                            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                    DisplayUtil.dip2px(SendPostActivity.this, 300));
                    webView.setVisibility(View.VISIBLE);
                    webView.setLayoutParams(layoutParams);
                    if ((!text.startsWith("http://")) && (!text.startsWith("https://"))) {
                        text = "https://" + text;
                    }
                    //如果不设置WebViewClient，请求会跳转系统浏览器
                    webView.setWebViewClient(new WebViewClient() {
                        //覆盖shouldOverrideUrlLoading 方法
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return true;
                        }
                    });
                    webView.loadUrl(text);
                    etUrl.setText(text);
                }
            }
        } else if (mDynamicType == 0) {
            //中间状态，三种类型都可选择
            ivPhoto.setImageAlpha(255);
            ivVideo.setImageAlpha(255);
            ivWeb.setImageAlpha(255);
            llWebLayout.setVisibility(View.GONE);
            llPhoto.setVisibility(View.GONE);
            rlVideo.setVisibility(View.GONE);
        }
    }

//    private void initRecyclerView() {
//        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//        recyclerView.setVisibility(View.GONE);
//        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
//        postSelectedImagesAdapter = new PostSelectedImagesAdapter(this, images);
//        recyclerView.setAdapter(postSelectedImagesAdapter);
//        postSelectedImagesAdapter.setOnPicDeletedListener(new PostSelectedImagesAdapter.OnPicDeletedListener() {
//            @Override
//            public void onPicDeleted(int position) {
//                images.remove(position);
//                postSelectedImagesAdapter.notifyItemRemoved(position);
//            }
//        });
//    }

    private void initBottomView() {
        ivVideo = (ImageView) findViewById(R.id.iv_video);
        ivVideo.setOnClickListener(this);
        ivWeb = (ImageView) findViewById(R.id.iv_ie);
        ivWeb.setOnClickListener(this);
        ivPhoto = (ImageView) findViewById(R.id.iv_photo);
        ivPhoto.setOnClickListener(this);
    }

    private void initWebListener() {

        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                LinearLayout.LayoutParams layoutParams =
                        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                DisplayUtil.dip2px(SendPostActivity.this, 200 + progress));
                webView.setLayoutParams(layoutParams);
                tvWebViewHeightView.setText(String.format(ResStringUtil.getString(R.string.zone_adjust_web_height), 200 + progress));

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void initGridListener() {
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //加号，选择图片
                if (position == mPictureList.size()) {
                    Intent intent = new Intent(SendPostActivity.this, JFPicturePickPhotoWallActivity.class);
                    ArrayList<String> tempList = new ArrayList<>();
                    for (int i = 0; i < mPictureList.size(); i++) {
                        tempList.add(mPictureList.get(i).getCloudFilePath());
                    }
                    intent.putExtra("mPictureList", tempList);
                    intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, 9);//可选择的最大照片数
                    intent.putExtra(JFPicturePickPhotoWallActivity.SHOW_RAW_PIC, false);//不显示原图
                    intent.putExtra("sendBtnName", getResources().getString(R.string.common_text_confirm));
                    intent.putExtra(JFPicturePickPhotoWallActivity.SELECT_MODE, JFPicturePickPhotoWallActivity.MODE_PIC_ONLY);
                    startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
                    overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        //图片说说，类型1
        if (id == R.id.iv_photo) {
            if (mDynamicType != 1) {
                if (mPictureList.size() > 0 || llWebLayout.getVisibility() != View.GONE || rlVideo.getVisibility() != View.GONE) {
                    return;
                }
                mDynamicType = 1;
                resetType();
            }
            Intent intent = new Intent(this, JFPicturePickPhotoWallActivity.class);
            ArrayList<String> tempList = new ArrayList<>();
            for (int i = 0; i < mPictureList.size(); i++) {
                tempList.add(mPictureList.get(i).getCloudFilePath());
            }
            intent.putExtra("mPictureList", tempList);
            intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, 9);//可选择的最大照片数
            intent.putExtra("sendBtnName", getResources().getString(R.string.common_text_confirm));
            intent.putExtra(JFPicturePickPhotoWallActivity.SELECT_MODE, JFPicturePickPhotoWallActivity.MODE_PIC_ONLY);
            intent.putExtra(JFPicturePickPhotoWallActivity.SHOW_RAW_PIC, false);
            startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
        } else if (id == R.id.iv_ie) {
            //网页说说，类型2
            if (mDynamicType != 2) {
                if (mPictureList.size() > 0 || llWebLayout.getVisibility() != View.GONE || rlVideo.getVisibility() != View.GONE) {
                    return;
                }
                mDynamicType = 2;
                resetType();
            }
        } else if (id == R.id.iv_video) {
            //视频说说，类型3
            if (mDynamicType != 3) {
                if (mPictureList.size() > 0 || llWebLayout.getVisibility() != View.GONE || rlVideo.getVisibility() != View.GONE) {
                    return;
                }
                mDynamicType = 3;
                resetType();
            }
            showVideoDialog();
//            Intent intent = new Intent(this, RecorderActivity.class);
//            intent.putExtra("showLocal",RecorderActivity.SELECT_VIDEO);
//            startActivityForResult(intent, AddZonePopWindow.REQUEST_CODE_SELECT_VIDEO);
//            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_top_out);

        } else if (id == R.id.iv_web_delete) {
            if (isSending) {
                ToastUtils.showShort(R.string.zone_send_not_delete);
                return;
            }
            webView.loadUrl(null);
            webView.setVisibility(View.GONE);
            etUrl.setText("");
            mDynamicType = 0;
            resetType();
        } else if (id == R.id.tv_save) {
            //发送
            if (isSending) {
                ToastUtil.showToast(SendPostActivity.this, R.string.zone_sending);
                return;
            }
            String content = etInput.getText().toString();
            sendNewDynamic(content);
        } else if (id == R.id.iv_video_delete) {
            if (isSending) {
                ToastUtils.showShort(R.string.zone_send_not_delete);
                return;
            }
            rlVideo.setVisibility(View.GONE);
            mDynamicType = 0;
            resetType();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PIC_SELECTE_CODE
                && resultCode == RESULT_OK) {
            if (data.getExtras().containsKey(JFPicturePickPhotoWallActivity.SELECTED_VIDEO)) {
                video_path = data.getExtras().getString(JFPicturePickPhotoWallActivity.SELECTED_VIDEO);
                mDynamicType = 3;
                resetType();
                rlVideo.setVisibility(View.VISIBLE);
//                if (com.utilcode.util.ImageUtils.save(ImageUtil.getVideoThumbnail(video_path),
//                        chatpath +  ImageUtil.getFileName(video_path) + ".pic" , Bitmap.CompressFormat.PNG)){
                LXGlideImageLoader.getInstance().displayImage(this, ivVideoImage, video_path);
//                }
                return;
            }
            //图库选择照片
            mPictureList.clear();
            ArrayList<ZoneCloudFile> tempCloudFiles = new ArrayList<>();
            ArrayList<String> tempList = (ArrayList<String>) data.getExtras().get("mSelectedPics");
            for (int i = 0; i < tempList.size(); i++) {
                ZoneCloudFile cloudFile = new ZoneCloudFile();
                cloudFile.setCloudFilePath(tempList.get(i));
                tempCloudFiles.add(cloudFile);
            }
            mPictureList.addAll(tempCloudFiles);
            if (mPictureList.size() > 0) {
                mDynamicType = 1;
                resetType();
            }
            adapter.notifyDataSetChanged();
        } else if (resultCode == RESULT_OK && requestCode == AddZonePopWindow.REQUEST_CODE_SELECT_VIDEO) {
            //录制视频完成
            video_path = data.getStringExtra("path");
            String videoTime = data.getStringExtra("videoTime");
            double fileSize = FileSizeUtil.getFileOrFilesSize(video_path, FileSizeUtil.SIZETYPE_KB);
            if (fileSize < 20) {
                //视频过小，录制失败，不发送消息
                ToastUtil.showToast(this, R.string.zone_video_record_fail);
                mDynamicType = 0;
                resetType();
                return;
            }
            rlVideo.setVisibility(View.VISIBLE);
            if (com.utilcode.util.ImageUtils.save(ImageUtil.getVideoThumbnail(video_path),
                    chatpath + ImageUtil.getFileName(video_path) + ".pic", Bitmap.CompressFormat.PNG)) {
                LXGlideImageLoader.getInstance().displayImage(this, ivVideoImage, chatpath + ImageUtil.getFileName(video_path) + ".pic");
            }

        } else if (resultCode == RESULT_CANCELED && mPictureList.size() == 0) {
            mDynamicType = 0;
            resetType();
        } else if (requestCode == 666 && resultCode == RESULT_OK) {
            if (data != null) {
                Uri selectedVideo = data.getData();
                String[] filePathColumn = {MediaStore.Video.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedVideo,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                video_path = cursor.getString(columnIndex);
//                Intent intent = new Intent();
//                intent.putExtra("path", cursor.getString(columnIndex));
//                setResult(RESULT_OK, intent);
                cursor.close();
                rlVideo.setVisibility(View.VISIBLE);
                LXGlideImageLoader.getInstance().displayImage(this, ivVideoImage, video_path);

            }
        }
    }

    /**
     * 发送新动态
     *
     * @param content 说说内容
     */
    @SuppressLint("NewApi")
    private void sendNewDynamic(String content) {
        isSending = true;
        String urlStr = etUrl.getText().toString();

        // 类型为说说
        if (mDynamicType == 1 || mDynamicType == 0) {
//            文字 图片都为空
            if ("".equals(content.trim()) && mPictureList.size() == 0) {
                ToastUtil.showToast(this, R.string.zone_ss_is_empty);
                isSending = false;
            }

            // 图片不为空
            else if (mPictureList.size() > 0) {
                LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.zone_ready_to_upload));
                //压缩图片上传
                ThreadPoolUtils.execute(new ThreadPoolUtils.Task() {
                    @Override
                    protected void work() {
                        if (mPictureList.size() == 1) {
                            String imgLocation = mPictureList.get(0).getCloudFilePath();
                            //是gif图 不压缩
                            if (ImageUtil.isGifFile((new File(imgLocation)))) {
                                uploadOneImage(imgLocation, ImageUtil.getPicScale(imgLocation));
                            } else {
                                String scale = ImageUtil.saveNewImage(imgLocation, 1280, 1280);
                                String img = chatpath + ImageUtil.getFileName(imgLocation) + ".pic";
                                uploadOneImage(img, scale);
                            }
                        } else {
                            ArrayList<ZoneCloudFile> uploadCloudFiles = new ArrayList<>();
                            for (ZoneCloudFile imgAddress : mPictureList) {
                                imgAddress.setCloudProgress(0);
                                //如果不是gif动图则进行裁剪压缩
                                if (!ImageUtil.isGifFile((new File(imgAddress.getCloudFilePath())))) {
                                    ImageUtil.saveNewImage(imgAddress.getCloudFilePath(), 1280, 1280);
                                    imgAddress.setCloudFilePath(chatpath + ImageUtil.getFileName(imgAddress.getCloudFilePath()) + ".pic");
                                    uploadCloudFiles.add(imgAddress);
//                            uploadImage(chatpath + ImageUtil.getFileName(imgAddress) + ".pic");
                                } else {
//                            uploadImage(imgAddress);
                                    imgAddress.setCloudFilePath(imgAddress.getCloudFilePath());
                                    uploadCloudFiles.add(imgAddress);
                                }
                            }
                            PansoftCloudUtil.syncMultiFileUpload(uploadCloudFiles, new PansoftCloudUtil.MultiUpLoadListener() {
                                @Override
                                public void uploadProgress(int position, int progress, PansoftCloudUtil.CloudFile cloudFile) {
                                    if (isFinishing() || isDestroyed()) {
                                        return;
                                    }
                                    Log.d("SendPost", position + "---" + progress);
                                    mPictureList.get(position).setCloudProgress(progress);
                                    adapter.notifyDataSetChanged();
                                }

                                @Override
                                public void upLoadFinish(List<String> urlList, List<? extends PansoftCloudUtil.CloudFile> cloudFileList) {
                                    if (isFinishing() || isDestroyed()) {
                                        return;
                                    }
                                    sendImg(urlList);
                                }

                                @Override
                                public void uploadFail(Object message) {
                                    LoadingDataUtilBlack.dismiss();
                                    ToastUtil.showToast(SendPostActivity.this, R.string.common_text_upload_fail_again);
                                    isSending = false;
                                }
                            });
                        }
                    }
                });

            } else {
                //图片为空
                sendOnlyText();
            }
        } else if (mDynamicType == 2) {
            //网页说说
            if ("".equals(urlStr)) {
                ToastUtil.showToast(this, R.string.zone_web_is_empty);
                isSending = false;
            } else if (!JFStringUtil.isHttpUrl(etUrl.getText().toString())) {
                ToastUtils.showShort(R.string.zone_input_correct_url);
                isSending = false;
            } else {
                sendUrl();
            }
        } else if (mDynamicType == 3) {
            //视频说说
            //文字 视频都为空
            LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.zone_ready_to_upload));

            if ("".equals(content) && video_path.equals("")) {
                ToastUtil.showToast(this, R.string.zone_ss_is_empty);
                isSending = false;
                return;
            }
            if (FileUtils.getFileLength(video_path) > 20 * 1024 * 1024) {
                ToastUtils.showShort(R.string.zone_video_large_m_please_select);
                isSending = false;
                return;
            }

//            int during = TimeUtils.getRingDuring(video_path);
//            if (during > 20000) {
//                ToastUtils.showShort(R.string.zone_video_large_s_please_select);
//                isSending = false;
//                return;
//            }
            // 视频不为空
            if (!video_path.equals("")) {
                sendVideo(content);
            } else {
                //视频为空
                sendOnlyText();
            }
        }

    }

//    /**
//     * 向云盘上传图片，上传完成后发送图片
//     *
//     * @param imgAddress 图片的本地路径
//     */
//    private void uploadImage(String imgAddress) {
//        PansoftCloudUtil.getCloudRes(imgAddress, new PansoftCloudUtil.UpLoadListener() {
//            @Override
//            public void getHttpUrl(Boolean isSuccess, String url) {
//                if (isSuccess) {
//                    Log.i(TAG, "---头像在云盘服务器上的路径:" + url);
//                    imgUrlList.add(url);
//                    if (mPictureList.size() == imgUrlList.size()) {
//                        LoadingDataUtilBlack.dismiss();
//                        sendImg();
//                    }
//                } else {
//                    LoadingDataUtilBlack.dismiss();
//                    imgUrlList.clear();
//                    ToastUtil.showToast(SendPostActivity.this, "发送出错请重试");
//                }
//            }
//        });
//    }

    /**
     * 上传单张图片并发送
     *
     * @param imgLocation 图片本地路径
     * @param scale       图片宽高比
     */
    @SuppressLint("NewApi")
    private void uploadOneImage(String imgLocation, String scale) {
        String[] scales = scale.split(":");
        final String strWidth = scales[0];
        final String strHeight = scales[1];

        final List<String> imglist = new ArrayList<>();

        PansoftCloudUtil.cloudUploadWithProgress(imgLocation, new PansoftCloudUtil.UpLoadListener() {
            @Override
            public void getHttpUrl(Boolean isSuccess, String url) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                if (isSuccess) {
                    Log.i(TAG, R.string.zone_path_of_head + url);
                    imglist.add(url);
                    String contentText = etInput.getText().toString();
                    String content = new CreateBeanUtil().createSingleImageContent(contentText, imglist, Integer.valueOf(strWidth), Integer.valueOf(strHeight));
                    TalksBean talksBean = new CreateBeanUtil().createTalksBean(2, deviceModel, content);
                    sendPost(talksBean);
                } else {
                    LoadingDataUtilBlack.dismiss();
                    isSending = false;
                    ToastUtil.showToast(SendPostActivity.this, R.string.common_text_upload_fail_again);
                }
            }
        }, new PansoftCloudUtil.ProgressListener() {
            @Override
            public void progress(String path, int percent) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                mPictureList.get(0).setCloudProgress(percent);
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 上传视频
     */
    @SuppressLint("NewApi")
    private void sendVideo(final String text) {
        LogUtils.aTag(TAG, video_path);
        PansoftCloudUtil.cloudUploadWithProgress(video_path, new PansoftCloudUtil.UpLoadListener() {
            @Override
            public void getHttpUrl(Boolean isSuccess, String url) {

                if (isFinishing() || isDestroyed()) {
                    return;
                }
                if (isSuccess) {
                    String content = new CreateBeanUtil().createVideoContent(text, url);
                    TalksBean talksBean = new CreateBeanUtil().createTalksBean(2, DeviceUtils.getModel(), content);
                    sendPost(talksBean);
                } else {
                    LoadingDataUtilBlack.dismiss();
                    isSending = false;
                    ToastUtil.showToast(SendPostActivity.this, R.string.common_text_send_fail);
                }
            }
        }, new PansoftCloudUtil.ProgressListener() {
            @Override
            public void progress(String path, int percent) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                videoProgressView.setVisibility(View.VISIBLE);
                videoProgressView.setProgress(percent);
                if (percent == 100) {
                    videoProgressView.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 只发送文字
     */
    private void sendOnlyText() {
        String contentText = etInput.getText().toString().trim();
        if ("".equals(contentText)) {
            isSending = false;
            ToastUtil.showToast(AppContext.getInstance(), R.string.zone_ss_is_empty);
            return;
        }
        String content = new CreateBeanUtil().createCommonContent(contentText, new ArrayList<String>());
        TalksBean talksBean = new CreateBeanUtil().createTalksBean(2, deviceModel, content);
        LoadingDataUtilBlack.show(SendPostActivity.this, ResStringUtil.getString(R.string.zone_sending));
        sendPost(talksBean);
    }

    /**
     * 发送网址
     */
    private void sendUrl() {
        String contentText = etInput.getText().toString();
        String urlText = etUrl.getText().toString();
        String content = new CreateBeanUtil().createWebContent(contentText, urlText, 300);
        TalksBean talksBean = new CreateBeanUtil().createTalksBean(2, deviceModel, content);


        sendPost(talksBean);
    }

    /**
     * 发送图片
     */
    private void sendImg(List<String> imgUrlList) {
        String contentText = etInput.getText().toString();
        String content = new CreateBeanUtil().createCommonContent(contentText, imgUrlList);
        TalksBean talksBean = new CreateBeanUtil().createTalksBean(2, deviceModel, content);


        sendPost(talksBean);

    }

    private void showVideoDialog() {
        String[] items = {ResStringUtil.getString(R.string.zone_shot), ResStringUtil.getString(R.string.zone_photo)};
        new AlertDialog.Builder(this).setCancelable(true)
                .setTitle(ResStringUtil.getString(R.string.zone_video))
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (i == 0) {
                            Intent intent = new Intent(SendPostActivity.this, RecorderActivity.class);
                            startActivityForResult(intent, AddZonePopWindow.REQUEST_CODE_SELECT_VIDEO);
                            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_top_out);

                        } else if (i == 1) {
//                            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
//                            startActivityForResult(intent, 666);

                            Intent intent = new Intent(SendPostActivity.this, JFPicturePickPhotoWallActivity.class);
                            intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, 1);//可选择的最大照片数
                            intent.putExtra("sendBtnName", getResources().getString(R.string.common_text_confirm));
                            intent.putExtra(JFPicturePickPhotoWallActivity.SELECT_MODE, JFPicturePickPhotoWallActivity.MODE_VIDEO_ONLY);
                            intent.putExtra(JFPicturePickPhotoWallActivity.MAX_VIDEO_DURATION, 60);//最长20s
                            intent.putExtra(JFPicturePickPhotoWallActivity.MAX_VIDEO_SIZE, 20);//最大20M
                            intent.putExtra(JFPicturePickPhotoWallActivity.SHOW_RAW_PIC, false);
                            startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
                        }
                        dialogInterface.dismiss();
                    }
                })
                .create().show();
    }

    /**
     * 发说说
     *
     * @param talksBean 说说消息体
     */
    private void sendPost(final TalksBean talksBean) {
        LogUtils.e("sendPost___________>>");
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        params.put("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));
        params.put("device", talksBean.getObj().getDevice());
        params.put("content", talksBean.getObj().getPostContent());
        ZoneRequestUtil.postCommonRequest(TAG, "shortposts", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    isSending = false;
                    JSONObject jsonObject = new JSONObject(response);
                    if ("101000".equals(jsonObject.optString("status"))) {
                        int shortPostId = jsonObject.optInt("shortpostid");

                        int integral = 0;
                        try {
                            JSONObject postObject = jsonObject.optJSONObject("shortpost");
                            integral = postObject.optInt("integral");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LoadingDataUtilBlack.dismiss();
                        TalksBean.ObjBean objBean = talksBean.getObj();
                        objBean.setIntegral(integral);
                        objBean.setId(shortPostId);
                        talksBean.setObj(objBean);
                        Intent intent = new Intent();
                        intent.putExtra("talksBean", talksBean);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        showFailAlert();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showFailAlert();
                }


            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                showFailAlert();
            }
        });
    }

    private void showFailAlert() {
        LoadingDataUtilBlack.dismiss();
        isSending = false;
        new AlertDialog.Builder(this).setTitle(R.string.common_text_hint)
                .setMessage(ResStringUtil.getString(R.string.zone_publish_fail))
                .setPositiveButton(ResStringUtil.getString(R.string.common_text_confirm), null)
                .show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
}
